import java.util.Arrays;

public class TestHeap {

    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void createHeap(int array[]) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }

        //建堆的时间复杂度是O(n)
        for (int p = (usedSize-1-1)/2; p >= 0; p--) {
            shiftDown(p, usedSize);
        }
    }

    /**
     *
     * @param root 是每棵子树根节点的下标
     * @param len 是每颗子树调整结束的结束条件
     * 向下调整的时间复杂度为O(logn)
     */
    private void shiftDown(int root, int len) {
        int parent = root;
        int child = parent*2+1;

        while (child < len) {
            if (child+1<len && elem[child] < elem[child+1]) {
                child++;
            }

            if (elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;

                parent = child;
                child = parent*2+1;
            } else {
                break;
            }
        }
    }

    public void push(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem, elem.length*2);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    private void shiftUp(int child) {
        int parent = (child-1)/2;

        //while (child > 0) {
        while (parent >= 0) {
            if (elem[parent] < elem[child]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;

                child = parent;
                parent = (child-1)/2;
            } else {
                break;
            }
        }
    }

    public void pollHeap() {
        if (isEmpty()) {
            System.out.println("优先级队列为空！");
            return;
        }

        elem[0] = elem[usedSize-1];
        --usedSize;
        shiftDown(0,usedSize);
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    public int peekHeap() {
        if (isEmpty()) {
            System.out.println("优先级队列为空！");
            return 0;
        }

        return elem[0];
    }

    public void heapSort() {
        int end = usedSize - 1;
        while (end > 0) {
            int tmp = elem[0];
            elem[0] = elem[end];
            elem[end] = tmp;
            shiftDown(0, end);
            end--;
        }
    }
}
